package io.renren.modules.file.service.impl;

import io.renren.modules.file.entity.FileRelate;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.Query;
import io.renren.common.utils.Pages;

import io.renren.modules.file.dao.FileDao;
import io.renren.modules.file.entity.FileEntity;
import io.renren.modules.file.service.FileService;


@Service("fileService")
public class FileServiceImpl extends ServiceImpl<FileDao, FileEntity> implements FileService {

    @Override
    public Pages<FileEntity> queryPage(FileEntity fileEntity) {
        QueryWrapper<FileEntity> qw = new QueryWrapper<>();

        String xtlx = fileEntity.getXtlx();
        String oriFileName = fileEntity.getOriFileName();

        if(StringUtils.isNotBlank(xtlx)) {
            qw.eq("xtlx", xtlx);
        } else {
            qw.in("xtlx", new Object [] {"安全管控清单", "规范", "超前地质预报", "课件", "法律法规"});
        }

        qw.likeLeft(StringUtils.isNotBlank(oriFileName), "ori_file_name", oriFileName);

        IPage<FileEntity> page = this.page(
                new Query<FileEntity>().getPage(fileEntity),
               qw
        );

        return new Pages<FileEntity>(page);
    }

    /**
     * 更新关联字段
     * @param fileRelate
     */
    @Override
    public void updateRelate(FileRelate fileRelate) {
        Long[] fileId = fileRelate.getFileId();
        Integer relateId = fileRelate.getRelateId();

        if(fileId != null) {
            for(Long id : fileId) {
                FileEntity fileEntity = this.getById(id);
                if(fileEntity != null) {
                    fileEntity.setRelateId(relateId);
                    this.updateById(fileEntity);
                }
            }
        }
    }

    @Override
    public List<FileEntity> listAll(FileEntity fileEntity) {
        String xtlx = fileEntity.getXtlx();
        Integer relateId = fileEntity.getRelateId();
        String fileType = fileEntity.getFileType();

        QueryWrapper<FileEntity> qw = new QueryWrapper<>();

        qw.eq(StringUtils.isNotBlank(xtlx), "xtlx", xtlx);
        qw.eq(relateId != null, "relate_id", relateId);
        qw.likeLeft(StringUtils.isNotBlank(fileType),"file_type", fileType);

        return this.list(qw);
    }

}